<template>
  <section class="chart">
    <el-row>
      <el-col class="index-warn half-warn leftHalf">
        <h4>任务运行分时分类统计</h4>
        <el-col :span="24">
          <div id="chartTask" class="citem" :style="colStyle16"></div>
        </el-col>
      </el-col>

      <el-col class="index-warn half-warn ">
        <h4>HDFS</h4>
        <el-col :span="12">
          <div id="chartHdfsTL" class="citem" :style="colStyle8"></div>
        </el-col>
        <el-col :span="12">
          <div id="chartCapacity" class="citem" :style="colStyle8"></div>
        </el-col>
      </el-col>

      <el-col class="index-warn half-warn leftHalf">
        <h4>HBASE</h4>
        <el-col :span="12">
          <div id="chartRegionServer" class="citem" :style="colStyle8"></div>
        </el-col>
        <el-col :span="12">
          <div id="chartRegionRPC" class="citem" :style="colStyle8"></div>
        </el-col>
      </el-col>

      <el-col class="index-warn half-warn">
        <h4>KAFKA</h4>
        <el-col :span="12">
          <div id="chartBytIAO" class="citem" :style="colStyle8"></div>
        </el-col>
        <el-col :span="12">
          <div id="chartMsgI" class="citem" :style="colStyle8"></div>
        </el-col>
      </el-col>

    </el-row>
  </section>
</template>

<script>
  import util from '../../common/util'
  import dao from '../../common/dao'
  import echarts from 'echarts'

  export default {
    components: {},
    props: ['refreshRate', 'dataValue', 'rTime','reSizeCode'],
    data() {
      return {
        colStyle16: "",
        colStyle8: "",
        chartTask: null,
        chartHdfsTL: null,
        chartCapacity: null,
        chartRegionServer: null,
        chartRegionRPC: null,
        chartBytIAO: null,
        chartMsgI: null,
      }
    },
    watch:{
      reSizeCode(n,o){
      window.onresize = this.resizeAllChart
      this.resizeAllChart()
      }
    },
    methods: {
      colStyle () {
        /*if (window.innerWidth == 1920) {
          this.colStyle16 = "width:785px;height:350px;";
          this.colStyle8 = "width:360px;height:350px;"
        } else if (window.innerWidth == 1366) {
          this.colStyle16 = "width:510px;height:350px;";
          this.colStyle8 = "width:255px;height:350px;"
        } else {
          this.colStyle16 = "width:517px;height:350px;";
          this.colStyle8 = "width:250px;height:350px;"
        }*/

        this.colStyle16 = "width:100%;height:350px;";
        this.colStyle8 = "width:100%;height:350px;"
      },
      bChartTask (timer, mapreduceData, sparkData, tezData) {

        var itemStyle = {
          normal: {},
          emphasis: {
            barBorderWidth: 1,
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowOffsetY: 0,
            shadowColor: 'rgba(0,0,0,0.5)'
          }
        };

        let option = {
          title: {
            text: '',
            left: 'left',
            x: 'center'
          },
          legend: {
            data: ['MapReduce', 'Hive', 'spark'],
            bottom: 0
          },
          tooltip: {},
          xAxis: {
            data: timer,
            name: '时间',
            silent: false,
            axisLine: {onZero: true},
            splitLine: {show: false},
            splitArea: {show: false},
            axisLabel: {
              formatter: function (value, index) {
                // 格式化成月/日，只在第一个刻度显示年份
                var date = new Date(value);
                var texts = [(date.getMonth() + 1), date.getDate()];
                if (index === 0) {
                //  texts.unshift(date.getYear());
                }
                return texts.join('/');
              }
            }
          },
          yAxis: {
            name: '数量',
          },
          grid: {
            left: 0,
            right: 0
          },
          series: [
            {
              name: 'MapReduce',
              type: 'bar',
              stack: 'one',
              itemStyle: itemStyle,
              data: mapreduceData
            },
            {
              name: 'Hive',
              type: 'bar',
              stack: 'one',
              itemStyle: itemStyle,
              data: tezData
            },
            {
              name: 'spark',
              type: 'bar',
              stack: 'one',
              itemStyle: itemStyle,
              data: sparkData
            },

          ]
        };

        this.chartTask = echarts.init(document.getElementById('chartTask'));
        this.chartTask.setOption(option);
      },
      bChartHdfsTL(timer, hdp01Data, hdp02Data){
        let option = {
          title: {
            text: 'HDFS负载总量'
          },
          tooltip: {
            trigger: 'axis'
          },
          legend: {
            data: ['hdp01', 'hdp02'],
            bottom: 0
          },
          grid: {
            containLabel: true
          },
          xAxis: [
            {
              type: 'category',
              name: '时间',
              boundaryGap: false,
              axisLabel: {
                formatter: function (value, index) {
                  // 格式化成月/日，只在第一个刻度显示年份
                  var date = new Date(value);
                  var texts = [(date.getMonth() + 1), date.getDate()];
                  if (index === 0) {
                    //texts.unshift(date.getYear());
                  }
                  return texts.join('/');
                }
              },
              data: timer
            }
          ],
          yAxis: [
            {
              type: 'value',
              name: '量',
            }
          ],
          series: [
            {
              name: 'hdp01',
              type: 'line',
              stack: '总量',
              data: hdp01Data
            },
            {
              name: 'hdp02',
              type: 'line',
              stack: '总量',
              data: hdp02Data
            }
          ]
        };
        this.chartHdfsTL = echarts.init(document.getElementById('chartHdfsTL'));
        this.chartHdfsTL.setOption(option);
      },
      bChartCapacity(timer = [], hdp01Data = []){
        let option = {
          title: {
            text: 'HDFS磁盘使用量'
          },
          tooltip: {
            trigger: 'axis'
          },
          legend: {
            data: ['hdp01'],
            bottom: 0
          },
          grid: {
            containLabel: true
          },
          xAxis: [
            {
              type: 'category',
              name: '时间',
              boundaryGap: false,
              axisLabel: {
                formatter: function (value, index) {
                  // 格式化成月/日，只在第一个刻度显示年份
                  var date = new Date(value);
                  var texts = [(date.getMonth() + 1), date.getDate()];
                  if (index === 0) {
                  //  texts.unshift(date.getYear());
                  }
                  return texts.join('/');
                }
              },
              data: timer
            }
          ],
          yAxis: [
            {
              name: '(Gib)',
              type: 'value'
            }
          ],
          series: [
            {
              name: 'hdp01',
              type: 'line',
              stack: '总量',
              data: hdp01Data
            },

          ]
        };
        this.chartCapacity = echarts.init(document.getElementById('chartCapacity'));
        this.chartCapacity.setOption(option);
      },
      bChartRegionServer(timer = [], mhMaxData= [], mhUsedData= [], mhCommiteData= [], mnhMaxData = [], mnhUsedData = [], mnhCommiteData = []){
        let option = {
          title: {
            text: 'RegionServer内存'
          },
          tooltip: {
            trigger: 'axis',
            position: function (pos, params, dom, rect, size) {
              // 鼠标在左侧时 tooltip 显示到右侧，鼠标在右侧时 tooltip 显示到左侧。
              /*var obj = {top: 60};
              obj[['left', 'right'][+(pos[0] < size.viewSize[0] / 2)]] = 5;
              return obj;*/
            }
          },
          legend: {
            data: ['Max', 'Used', 'Committed', 'NonMax', 'NonUsed', 'NonCommitted'],
            bottom: 0
          },
          grid: {
            containLabel: true
          },
          xAxis: [
            {
              type: 'category',
              name: '时间',
              boundaryGap: false,
              axisLabel: {
                formatter: function (value, index) {
                  // 格式化成月/日，只在第一个刻度显示年份
                  var date = new Date(value);
                  var texts = [(date.getMonth() + 1), date.getDate()];
                  if (index === 0) {
                  //  texts.unshift(date.getYear());
                  }
                  return texts.join('/');
                }
              },
              data: timer
            }
          ],
          yAxis: [
            {
              name: '(Gib)',
              type: 'value'
            }
          ],
          series: [
            {
              name: 'Max',
              type: 'line',
              data: mhMaxData
            },
            {
              name: 'Used',
              type: 'line',
              data: mhUsedData
            },
            {
              name: 'Committed',
              type: 'line',
              data: mhCommiteData
            },
            {
              name: 'NonMax',
              type: 'line',
              data: mnhMaxData
            },
            {
              name: 'NonUsed',
              type: 'line',
              data: mnhUsedData
            },
            {
              name: 'NonCommitted',
              type: 'line',
              data: mnhCommiteData
            },

          ]
        };
        this.chartRegionServer = echarts.init(document.getElementById('chartRegionServer'));
        this.chartRegionServer.setOption(option);
      },
      bChartRegionRPC(timer = [], countData = [], handlerData = [], connerData = []){
        let option = {
          title: {
            text: 'RegionServer RPC'
          },
          tooltip: {
            trigger: 'axis'
          },
          legend: {
            data: ['rpcCount', 'numActiveHander', 'numOpenConnections'],
            bottom: 0
          },
          grid: {
            containLabel: true
          },
          xAxis: [
            {
              type: 'category',
              name: '时间',
              boundaryGap: false,
              axisLabel: {
                formatter: function (value, index) {
                  // 格式化成月/日，只在第一个刻度显示年份
                  var date = new Date(value);
                  var texts = [(date.getMonth() + 1), date.getDate()];
                  if (index === 0) {
                  //  texts.unshift(date.getYear());
                  }
                  return texts.join('/');
                }
              },
              data: timer
            }
          ],
          yAxis: [
            {
              name: '量',
              type: 'value'
            }
          ],
          series: [
            {
              name: 'rpcCount',
              type: 'line',
              data: countData
            },

            {
              name: 'numActiveHander',
              type: 'line',
              data: handlerData
            },
            {
              name: 'numOpenConnections',
              type: 'line',
              data: connerData
            },
          ]
        };
        this.chartRegionRPC = echarts.init(document.getElementById('chartRegionRPC'));
        this.chartRegionRPC.setOption(option);
      },
      bChartBytIAO(timer = [], BIData = [], BOData = []){
        let option = {
          title: {
            text: '写入写出'
          },
          tooltip: {
            trigger: 'axis'
          },
          legend: {
            data: ['Bytes In', 'Bytes Out'],
            bottom: 0
          },
          grid: {
            containLabel: true
          },
          xAxis: [
            {
              type: 'category',
              name: '时间',
              boundaryGap: false,
              axisLabel: {
                formatter: function (value, index) {
                  // 格式化成月/日，只在第一个刻度显示年份
                  var date = new Date(value);
                  var texts = [(date.getMonth() + 1), date.getDate()];
                  if (index === 0) {
                  //  texts.unshift(date.getYear());
                  }
                  return texts.join('/');
                }
              },
              data: timer
            }
          ],
          yAxis: [
            {
              name: 'Mib',
              type: 'value'
            }
          ],
          series: [
            {
              name: 'Bytes In',
              type: 'line',
              areaStyle: {normal: {}},
              data: BIData
            },
            {
              name: 'Bytes Out',
              type: 'line',
              areaStyle: {normal: {}},
              data: BOData
            },
          ]
        };
        this.chartBytIAO = echarts.init(document.getElementById('chartBytIAO'));
        this.chartBytIAO.setOption(option);

      },
      bChartMsgI(timer = [], messageInData = []) {
        let option = {
          title: {
            text: '信息条数'
          },
          tooltip: {
            trigger: 'axis'
          },
          legend: {
            data: ['Messages In'],
            bottom: 0
          },
          grid: {
            containLabel: true
          },
          xAxis: [
            {
              type: 'category',
              name: '时间',
              boundaryGap: false,
              axisLabel: {
                formatter: function (value, index) {
                  // 格式化成月/日，只在第一个刻度显示年份
                  var date = new Date(value);
                  var texts = [(date.getMonth() + 1), date.getDate()];
                  if (index === 0) {
                  //  texts.unshift(date.getYear());
                  }
                  return texts.join('/');
                }
              },
              data: timer
            }
          ],
          yAxis: [
            {
              name: '条数',
              type: 'value'
            }
          ],
          series: [
            {
              name: 'Messages In',
              type: 'line',
              areaStyle: {normal: {}},
              data: messageInData
            }
          ]
        };
        this.chartMsgI = echarts.init(document.getElementById('chartMsgI'));
        this.chartMsgI.setOption(option);
      },

      /* 获取数据 */
      getAppsStateHttp () { //任务运行分时分类统计 请求

        let arg = {
          "starttime": this.rTime[0],
          "endtime": this.rTime[1]
        };
        dao.getAppsState(arg).then((response) => {

          if (this.$route.name !== '平台监控') {return false}
          let timer, mapreduceData, sparkData, tezData;

          let resParm = response.body;
          if (!resParm.data) {return false}
          let data = JSON.parse(resParm.data);

          timer = data.time || [];
          mapreduceData = data.MAPREDUCE || [];
          sparkData = data.SPARK || [];
          tezData = data.TEZ || [];

          this.bChartTask(timer, mapreduceData, sparkData, tezData);

        })
      },
      getHdfsLoadTotalHttp () { //HDFS负载总量 请求

        let arg = {
          "metricNames": "dfs.FSNamesystem.TotalLoad",
          "hostname": "%",
          "app_id": "namenode",
          "starttime": this.rTime[0],
          "endtime": this.rTime[1]
        };
        dao.getHdfsLoadTotal(arg).then((response) => {
          if (this.$route.name !== '平台监控') {return false}

          let [timer, hdp01Data, hdp02Data] = [[], [], []];

          let rParam = response.body;
          if (!rParam.results) {return false}

          let hdp01 = rParam.results[0] || [];
          let hdp02 = rParam.results[1] || [];

          for (let i = 0; i < hdp01.y.length; i++) {
            hdp01Data.push((hdp01.y[i]).toFixed(2));
          }
          for (let i = 0; i < hdp02.y.length; i++) {
            hdp02Data.push((hdp02.y[i]).toFixed(2));
          }

        //  时间转换
          if (hdp01.x.length) {
            for (let i = 0; i < hdp01.x.length; i++) {
              timer.push(util.pokeToTime(hdp01.x[i]));
            }
          } else if (hdp02.x.length) {
            for (let i = 0; i < hdp02.x.length; i++) {
              timer.push(util.pokeToTime(hdp01.x[i]));
            }
          } else {
            x = 0;
          }
          this.bChartHdfsTL(timer, hdp01Data, hdp02Data);

        })

      },
      getHdfsCapacityInfoHttp () { //HDFS磁盘使用量 请求
        let arg = {
          "metricNames": "dfs.FSNamesystem.CapacityUsedGB",
          "app_id": "namenode",
          "starttime": this.rTime[0],//开始时间戳
          "endtime": this.rTime[1]//结束时间戳
        };
        dao.getHdfsCapacityInfo(arg).then((response) => {
          if (this.$route.name !== '平台监控') {return false}
          let [timer, hdp01Data] = [[], []];
          let rParm = response.body;
          if (!rParm.results) {return false}
          let hdp01 = response.body.results[0] || [];
          for (let i = 0; i < hdp01.y.length; i++) {
            hdp01Data.push((hdp01.y[i]).toFixed(2));
          }
          for (let i = 0; i < hdp01.x.length; i++) {
            timer.push(util.pokeToTime(hdp01.x[i]));
          }
          this.bChartCapacity(timer, hdp01Data);
        })

      },
      getHbaseRegionServerMemsLayoutHttp () {//RegionServer 内存分布 请求
        let arg = {
          "metricNames": "jvm.RegionServer.JvmMetrics.MemHeapMaxM,jvm.RegionServer.JvmMetrics.MemHeapCommittedM,jvm.RegionServer.JvmMetrics.MemHeapUsedM,jvm.RegionServer.JvmMetrics.MemNonHeapMaxM,jvm.RegionServer.JvmMetrics.MemNonHeapUsedM,jvm.RegionServer.JvmMetrics.MemNonHeapCommittedM",
          //"metricNames": "jvm.metrics.maxMemoryM,jvm.metrics.memHeapCommittedM,jvm.metrics.memHeapUsedM,jvm.metrics.memNonHeapUsedM,jvm.metrics.memNonHeapCommittedM",
          "app_id": "hbase",
          "starttime": this.rTime[0],//开始时间戳
          "endtime": this.rTime[1]//结束时间戳
        };
        dao.getHbaseRegionServerMemsLayout(arg).then((response) => {
          // success
          if (this.$route.name !== '平台监控') {return false}
          let [timer, mhMaxData, mhUsedData, mhCommiteData, mnhMaxData, mnhUsedData, mnhCommiteData] = [[], [], [], [], [], [], []];

          if (!response.body.resultMap) {return false}
          let rParam = response.body.resultMap;
          if('object' != typeof rParam) return false
          let mhMax = rParam.x_0||[];
          mhMax = mhMax[0] || [];
          let mhUsed = rParam.x_1 || [];
          mhUsed = mhUsed[0] || [];

          let mhCommite = rParam.x_2 || [];
          mhCommite = mhCommite[0] || [];

          let mnhMax = rParam.x_3 || [];
          mnhMax = mnhMax[0] || [];

          let mnhUsed = rParam.x_4 || [];
          mnhUsed = mnhUsed[0] || [];

          let mnhCommite = rParam.x_5 || [];
          mnhCommite = mnhCommite[0] || [];

          for (let i = 0; i < mhMax.y.length; i++) {
            mhMaxData.push((mhMax.y[i]).toFixed(2));
          }
          for (let i = 0; i < mhUsed.y.length; i++) {
            mhUsedData.push((mhUsed.y[i]).toFixed(2));
          }
          for (let i = 0; i < mhCommite.y.length; i++) {
            mhCommiteData.push((mhCommite.y[i]).toFixed(2));
          }
          for (let i = 0; i < mnhMax.y.length; i++) {
            mnhMaxData.push((mnhMax.y[i]).toFixed(2));
          }
          for (let i = 0; i < mnhUsed.y.length; i++) {
            mnhUsedData.push((mnhUsed.y[i]).toFixed(2));
          }
          for (let i = 0; i < mnhCommite.y.length; i++) {
            mnhCommiteData.push((mnhCommite.y[i]).toFixed(2));
          }

          for (let i = 0; i < mhMax.x.length; i++) {
            timer.push(util.pokeToTime(mhMax.x[i]));
          }

          this.bChartRegionServer(timer, mhMaxData, mhUsedData, mhCommiteData, mnhMaxData, mnhUsedData, mnhCommiteData);

        })
      },
      getHbaseRegionServerRpcHttp () {//RegionServer RPC 请求
        let arg = {
          "metricNames": "jvm.RegionServer.JvmMetrics.MemHeapMaxM._avg,regionserver.RegionServer.numActiveHandler._avg,regionserver.RegionServer.numOpenConnections._avg",
          "app_id": "hbase",
          "starttime": this.rTime[0],
          "endtime": this.rTime[1]
        };
        dao.getHbaseRegionServerRpc(arg).then((response) => {
          if (this.$route.name !== '平台监控') {return false}

          let [timer, countData, handlerData, connerData] = [[], [], [], []];
          if (!response.body.resultMap) {return false}
          let rParam = response.body.resultMap;
          if('object' != typeof rParam) return false

          let count = rParam.x_0[0] || [];
          let handler = rParam.x_1[0] || [];
          let conner = rParam.x_2[0] || [];

          for (let i = 0; i < count.y.length; i++) {
            countData.push((count.y[i]).toFixed(2));
          }
          for (let i = 0; i < handler.y.length; i++) {
            handlerData.push((handler.y[i]).toFixed(2));
          }
          for (let i = 0; i < conner.y.length; i++) {
            connerData.push((conner.y[i]).toFixed(2));
          }

          if (count.x.length) {
            for (let i = 0; i < count.x.length; i++) {
              timer.push(util.pokeToTime(count.x[i]));
            }
          } else if (handler.x.length) {

          } else if (conner.x.length) {

          } else {
            x = 0;
          }
          this.bChartRegionRPC(timer, countData, handlerData, connerData);

        })
      },
      getKafkaBytesInOrOutPerSecHttp () { //KAFKA 输入输出字节数 请求

        let arg = {
          "metricNames": "kafka.server.BrokerTopicMetrics.BytesInPerSec.count._avg,kafka.server.BrokerTopicMetrics.BytesOutPerSec",
          "app_id": "kafka_broker",
          "starttime": this.rTime[0], //开始时间戳
          "endtime": this.rTime[1] //结束时间戳
        };

        dao.getKafkaBytesInOrOutPerSec(arg).then((response) => {
          // success
          if (this.$route.name !== '平台监控') {return false}
          if (response.body.retCode != 200) { return false }

          let [timer, BIData, BOData] = [[], [], []];

          let rParm = response.body;
          let rData = rParm.resultMap.x_0[0] || [];
          let BI = rData.y || []; //输入
          let BO = rData.y_0 || []; //输出

          for (let i = 0; i < BI.length; i++) {
            BIData.push((BI[i]).toFixed(2));
          }
          for (let i = 0; i < BO.length; i++) {
            BOData.push((BO[i]).toFixed(2));
          }

        //  时间转换
          if (rData.x.length) {
            for (let i = 0; i < rData.x.length; i++) {
              timer.push(util.pokeToTime(rData.x[i]));
            }
          } else if (rData.x_0.length) {
            for (let i = 0; i < hdp02.x.length; i++) {
              timer.push(util.pokeToTime(rData.x_0[i]));
            }
          } else {
            x = 0;
          }
          this.bChartBytIAO(timer, BIData, BOData);
        })

      },
      getKafkaMessagesInPerSecHttp () { //KAFKA 消息数 请求

        let arg = {
          "metricNames": "kafka.server.BrokerTopicMetrics.MessagesInPerSec.count._avg",
          "app_id": "kafka_broker",
          "starttime": this.rTime[0],//开始时间戳
          "endtime": this.rTime[1]//结束时间戳
        };
        dao.getKafkaMessagesInPerSec(arg).then((response) => {
          if (this.$route.name !== '平台监控') {return false}
          if (response.body.retCode != 200) { return false }
          let [timer, messageInData] = [[], []];
          let messageIn = response.body.results[0] || [];

          for (let i = 0; i < messageIn.y.length; i++) {
            messageInData.push((messageIn.y[i]).toFixed(2));
          }
          for (let i = 0; i < messageIn.x.length; i++) {
            timer.push(util.pokeToTime(messageIn.x[i]));
          }

          this.bChartMsgI(timer, messageInData);

        })

      },

      resizeAllChart(){
        this.chartTask.resize()
        this.chartHdfsTL.resize()
        this.chartCapacity.resize()
        this.chartRegionServer.resize()
        this.chartRegionRPC.resize()
        this.chartBytIAO.resize()
        this.chartMsgI.resize()
      },
    },
    beforeMount () {
      this.colStyle()
    },
    mounted () {
      this.bChartTask()
      this.bChartHdfsTL()
      this.bChartCapacity()
      this.bChartRegionServer()
      this.bChartRegionRPC()
      this.bChartBytIAO()
      this.bChartMsgI()


      this.$nextTick(() => {
        this.getAppsStateHttp();

        this.getHdfsLoadTotalHttp();
        this.getHdfsCapacityInfoHttp();

        this.getHbaseRegionServerMemsLayoutHttp();
        this.getHbaseRegionServerRpcHttp();

        this.getKafkaBytesInOrOutPerSecHttp();
        this.getKafkaMessagesInPerSecHttp();
      })

    }
  }
</script>

<style scoped>
  body {
    box-sizing: border-box;
  }
  h4{
    color: #999;
  }
  .half-warn {
    width: 49%;
  }

  .leftHalf {
    margin-right: 2%;
  }

  .index-warn {
    padding: 10px;
    margin-bottom: 20px;
    border: 1px solid #ccc;
  }
</style>